package com.carpool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;


public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {	
	@SuppressWarnings("unused")
	private static final int CIRCLERADIUS = 2;

	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private Context mContext;
	private GeoPoint geopoint;
	@SuppressWarnings("unused")
	private int number;

	public MyItemizedOverlay(Drawable defaultMarker) {
		super(boundCenterBottom(defaultMarker));
	}

	public MyItemizedOverlay(Drawable defaultMarker, Context context, GeoPoint point, int number) {
		super(boundCenterBottom(defaultMarker));
		mContext = context;
		geopoint = point;
		this.number = number;
		populate();
	}

	@Override
	protected OverlayItem createItem(int i) {
		return mOverlays.get(i);
	}

	@Override
	public int size() {
		return mOverlays.size();
	}

	public void addOverlay(OverlayItem overlay) {
		mOverlays.add(overlay);
		populate();
	}

	@Override
	protected boolean onTap(int index) {
		Geocoder geoCoder = new Geocoder(mContext, Locale.getDefault());
		try {
			List<Address> addresses = geoCoder.getFromLocation(geopoint.getLatitudeE6()/1E6, geopoint.getLongitudeE6()/1E6, 1);

			String add = "";
			if (addresses.size() > 0) 
			{
				for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
				i++)
					add += addresses.get(0).getAddressLine(i) + "\n";
			}

			Toast.makeText(mContext, add, Toast.LENGTH_SHORT).show();
		}
		catch (IOException e) {                
			e.printStackTrace();
		}   
		return true;
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		// Transform geoposition to Point on canvas
		Projection projection = mapView.getProjection();
		Point point = new Point();
		projection.toPixels(geopoint, point);

		// text "My Location"
		Paint text = new Paint();
		text.setAntiAlias(true);
		text.setColor(Color.BLACK);
		text.setTextSize(12);
		text.setTypeface(Typeface.MONOSPACE);

		//canvas.drawText(Integer.toString(number), point.x+3*CIRCLERADIUS, point.y+3*CIRCLERADIUS, text);

		populate();
		super.draw(canvas, mapView, shadow);

	}


}